<?php

/**
 * 服务器上传图片
 */

namespace app\api\controller;


class Upload extends Base
{
    public $extensions = array(
        'image/bmp' => 'bmp',
//        'image/gif' => 'gif',
        'image/jpeg' => 'jpg',
        'image/png' => 'png'
//        'image/x-icon' => 'ico'
    );
    //允许上传图片格式
    public $exts = ['jpg', 'bmp', 'png', 'jpeg'];

    public function index()
    {
        $post = post();
        $res = $this->serviceVerify($post['verify']);
        if ($res['state'] == false) {
            return $this->returnJson($res['msg']);
        }
        $data = $res['data'];
//        d($data);
        $action = spost('action');
        switch ($action) {
            case 'local'://上传本地图片
                $this->uploadLocal($data);
                break;
            case 'sslurl'://上传远程图片
                $this->uploadUlr($data, $post);
                break;
            default:
                $this->returnJson("服务器验证失败！");
                break;
        }
    }

    /**
     * 上传本地图片
     * @param array $data
     */
    private function uploadLocal($data = [])
    {
        $dir = '/files/' . $data['user_id'] . '/product/' . $data['date'] . "/" . $data['guid'] . "/";
        $file = $_FILES['imgs'];
        $rootpath = server('DOCUMENT_ROOT');
        $path = $rootpath . $dir;
        if (!is_dir($path)) {
            if (!mkdir($path, 0777, true)) {
                $this->returnJson('没有权限创建目录');
            }
        }
        $fname = htmlspecialchars($file["name"], ENT_QUOTES);
        if ($file["error"] > 0) {
            $this->returnJson("文件  " . $fname . " 上传时出错");
        }
        //文件后缀
        $extension = strtolower(pathinfo($fname, PATHINFO_EXTENSION));
        if (!in_array($extension, $this->exts)) {
            $this->returnJson("只允许上传" . join(',', $this->exts) . "格式的图片");
        }
        $name = md5(microtime() . $file["name"]) . '.' . $extension;
        $ret = move_uploaded_file($file["tmp_name"], $path . $name);
        if ($ret === false) {
            $this->returnJson('上传失败，请重试');
        }
        $files = array(
            'name' => $name,
            'path' => $dir . $name,
            'size' => $file['size'],
            'sign' => $data['sign']
        );

        $logpath = $rootpath . "/uploadlog/" . $data['user_id'] . '_product_' . $data['date'] . '_' . $data['guid'];
        if (file_exists($logpath)) {
            shell_exec("rm " . $logpath . " -r");
        }
        shell_exec("touch " . $logpath);
        $this->returnJson('上传成功', true, $files);
    }

    private function uploadUlr($data = [])
    {
        $url = spost('url');
        $header_array = get_headers($url, true);
        $size = $header_array['Content-Length'];//单位：字节B
        if ($size == 0) {
            $this->returnJson("UnImage");
        }

        $dir = '/files/' . $data['user_id'] . '/product/' . $data['date'] . "/" . $data['guid'] . "/";
        $rootpath = server('DOCUMENT_ROOT');
        $path = $rootpath . $dir;

        if (isset($this->extensions[$header_array['Content-Type']])) {
            $extension = $this->extensions[$header_array['Content-Type']];
        } else {
            $extension = '';
            $img_type = strtolower($header_array['Content-Type']);
            foreach ($this->extensions as $key => $value) {
                if (strstr($img_type, $key)) {
                    $extension = $value;
                    break;
                }
            }
            if ($extension == '') {
                $this->returnJson("只允许" . join(',', $this->exts) . "格式的图片");
            }
        }

//        if (!in_array($extension, $this->exts)) {
//            $this->returnJson("只允许" . join(',', $this->exts) . "格式的图片");
//        }
        if (!is_dir($path)) {
            if (!mkdir($path, 0777, true)) {
                $this->returnJson('没有权限创建目录');
            }
        }

        $name = md5(microtime() . $this->randomkeys(8)) . '.' . $extension;
        $this->downloadImgUrl($url, $path . $name);

        $files = array(
            'name' => $name,
            'path' => $dir . $name,
            'size' => $size,
            'sign' => $data['sign']
        );

        $logpath = $rootpath . "/uploadlog/" . $data['user_id'] . '_product_' . $data['date'] . '_' . $data['guid'];
        if (file_exists($logpath)) {
            shell_exec("rm " . $logpath . " -r");
        }
        shell_exec("touch " . $logpath);
        $this->returnJson('上传成功', true, $files);
    }

    private function randomkeys($length)
    {
        $str = null;
        $strPol = "1234567890";//大小写字母以及数字
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];
        }
        return $str;
    }

    private function downloadImgUrl($url, $path)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $resource = fopen($path, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }
}